from fastapi import FastAPI, HTTPException, status
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from datetime import datetime
import json
import os
from typing import List, Optional

app = FastAPI(title="BBS 评论系统")

# 挂载static文件夹，让后端能访问静态文件
app.mount("/static", StaticFiles(directory="static", html=True), name="static")

# 数据存储文件路径
DATA_FILE = "bbs_data.json"

# 评论数据模型
class Comment(BaseModel):
    id: Optional[int] = None
    content: str
    author: str
    parent_id: Optional[int] = None  # 用于回复功能，None表示是顶级评论
    created_at: Optional[datetime] = None

# 初始化数据文件
def init_data_file():
    if not os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False)

# 加载所有评论
def load_comments() -> List[Comment]:
    init_data_file()
    with open(DATA_FILE, 'r', encoding='utf-8') as f:
        try:
            comments_data = json.load(f)
            return [Comment(**item) for item in comments_data]
        except json.JSONDecodeError:
            return []

# 保存评论
def save_comments(comments: List[Comment]):
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        comments_dict = [comment.dict() for comment in comments]
        json.dump(comments_dict, f, ensure_ascii=False, default=str)

# 获取所有评论
@app.get("/comments", response_model=List[Comment])
def get_comments():
    return load_comments()

# 获取单条评论
@app.get("/comments/{comment_id}", response_model=Comment)
def get_comment(comment_id: int):
    comments = load_comments()
    for comment in comments:
        if comment.id == comment_id:
            return comment
    raise HTTPException(status_code=404, detail="评论不存在")

# 创建新评论
@app.post("/comments", response_model=Comment, status_code=status.HTTP_201_CREATED)
def create_comment(comment: Comment):
    comments = load_comments()
    
    # 生成新ID
    new_id = max([c.id for c in comments], default=0) + 1
    
    # 创建新评论对象
    new_comment = Comment(
        id=new_id,
        content=comment.content,
        author=comment.author,
        parent_id=comment.parent_id,
        created_at=datetime.now()
    )
    
    # 添加并保存
    comments.append(new_comment)
    save_comments(comments)
    
    return new_comment

# 更新评论
@app.put("/comments/{comment_id}", response_model=Comment)
def update_comment(comment_id: int, updated_comment: Comment):
    comments = load_comments()
    
    for i, comment in enumerate(comments):
        if comment.id == comment_id:
            # 确保ID不变
            updated = updated_comment.dict()
            updated['id'] = comment_id
            updated['created_at'] = comment.created_at  # 保持创建时间不变
            
            comments[i] = Comment(** updated)
            save_comments(comments)
            return comments[i]
    
    raise HTTPException(status_code=404, detail="评论不存在")

# 删除评论
@app.delete("/comments/{comment_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_comment(comment_id: int):
    comments = load_comments()
    
    # 检查评论是否存在
    comment_exists = any(c.id == comment_id for c in comments)
    if not comment_exists:
        raise HTTPException(status_code=404, detail="评论不存在")
    
    # 删除评论及其所有回复
    filtered_comments = [
        c for c in comments 
        if c.id != comment_id and c.parent_id != comment_id
    ]
    
    save_comments(filtered_comments)
    return None
#
# # 简单的前端页面
# @app.get("/")
# def read_root():
#     return """
#     <html>
#         <head>
#             <title>BBS 评论系统</title>
#             <style>
#                 body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
#                 .comment { border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 4px; }
#                 .reply { margin-left: 20px; border-left: 2px solid #666; }
#                 form { margin: 20px 0; padding: 20px; border: 1px solid #eee; border-radius: 4px; }
#                 input, textarea { width: 100%; padding: 8px; margin: 5px 0 15px; border: 1px solid #ddd; border-radius: 4px; }
#                 button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; }
#                 button:hover { background-color: #45a049; }
#             </style>
#         </head>
#         <body>
#             <h1>BBS 评论区</h1>
#
#             <form id="commentForm">
#                 <h3>发表评论</h3>
#                 <input type="text" id="author" placeholder="你的名字" required>
#                 <textarea id="content" rows="3" placeholder="请输入评论内容..." required></textarea>
#                 <input type="hidden" id="parentId" value="">
#                 <button type="submit">提交评论</button>
#             </form>
#
#             <div id="commentsContainer"></div>
#
#             <script>
#                 // 获取所有评论并显示
#                 async function loadComments() {
#                     const response = await fetch('/comments');
#                     const comments = await response.json();
#                     renderComments(comments);
#                 }
#
#                 // 渲染评论
#                 function renderComments(comments) {
#                     const container = document.getElementById('commentsContainer');
#                     container.innerHTML = '';
#
#                     // 先显示顶级评论，再显示回复
#                     const topLevelComments = comments.filter(c => c.parent_id === null);
#
#                     topLevelComments.forEach(comment => {
#                         container.appendChild(createCommentElement(comment, comments));
#                     });
#                 }
#
#                 // 创建评论元素
#                 function createCommentElement(comment, allComments) {
#                     const div = document.createElement('div');
#                     div.className = 'comment';
#                     div.innerHTML = `
#                         <strong>${comment.author}</strong>
#                         <small> ${new Date(comment.created_at).toLocaleString()}</small>
#                         <p>${comment.content}</p>
#                         <button onclick="replyTo(${comment.id})">回复</button>
#                         <button onclick="deleteComment(${comment.id})">删除</button>
#                     `;
#
#                     // 添加回复
#                     const replies = allComments.filter(c => c.parent_id === comment.id);
#                     replies.forEach(reply => {
#                         const replyDiv = createCommentElement(reply, allComments);
#                         replyDiv.className = 'comment reply';
#                         div.appendChild(replyDiv);
#                     });
#
#                     return div;
#                 }
#
#                 // 提交评论
#                 document.getElementById('commentForm').addEventListener('submit', async (e) => {
#                     e.preventDefault();
#
#                     const comment = {
#                         author: document.getElementById('author').value,
#                         content: document.getElementById('content').value,
#                         parent_id: document.getElementById('parentId').value || null
#                     };
#
#                     await fetch('/comments', {
#                         method: 'POST',
#                         headers: { 'Content-Type': 'application/json' },
#                         body: JSON.stringify(comment)
#                     });
#
#                     // 重置表单
#                     document.getElementById('commentForm').reset();
#                     document.getElementById('parentId').value = '';
#
#                     // 重新加载评论
#                     loadComments();
#                 });
#
#                 // 回复功能
#                 function replyTo(commentId) {
#                     document.getElementById('parentId').value = commentId;
#                     document.getElementById('content').focus();
#                 }
#
#                 // 删除评论
#                 async function deleteComment(commentId) {
#                     if (confirm('确定要删除这条评论吗？')) {
#                         await fetch(`/comments/${commentId}`, { method: 'DELETE' });
#                         loadComments();
#                     }
#                 }
#
#                 // 初始加载评论
#                 loadComments();
#             </script>
#         </body>
#     </html>
#     """

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
